package com.gsbelarus.gedemin.salary.fragment.gdmsg;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.gsbelarus.gedemin.salary.App;
import com.gsbelarus.gedemin.salary.R;
import com.gsbelarus.gedemin.salary.database.RealmHelper;
import com.gsbelarus.gedemin.salary.entity.model.GdMsgHolidayModel;
import com.gsbelarus.gedemin.salary.entity.model.GdMsgModel;
import com.gsbelarus.gedemin.salary.service.SendMsgDataService;
import com.gsbelarus.gedemin.salary.util.ExtractStringHelper;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import com.wdullaer.materialdatetimepicker.time.RadialPickerLayout;
import com.wdullaer.materialdatetimepicker.time.TimePickerDialog;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import io.realm.Realm;

public class GdMsgNewHolidayFragment extends Fragment implements DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener {

    public static final String DATEPICKER_START_TAG = "datepickerStart";
    public static final String DATEPICKER_FINISH_TAG = "datepickerFinish";
    public static final String TIMEPICKER_START_TAG = "timepickerStart";
    public static final String TIMEPICKER_FINISH_TAG = "timepickerFinish";

    private TextView tvStartDate;
    private TextView tvFinishDate;
    private TextView tvStartTime;
    private TextView tvFinishTime;

    private GdMsgModel gdMsgHoliday;
    private GdMsgHolidayModel gdMsgHolidaySubModel;

    private RealmHelper realmHelper;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setHasOptionsMenu(true);

        realmHelper = new RealmHelper(Realm.getInstance(getActivity()));

        gdMsgHoliday = new GdMsgModel();
        gdMsgHolidaySubModel = new GdMsgHolidayModel();

        Calendar now = Calendar.getInstance();
        now.set(Calendar.HOUR_OF_DAY, 0);
        now.set(Calendar.MINUTE, 0);
        now.set(Calendar.SECOND, 0);
        gdMsgHolidaySubModel.setDateBegin(now.getTime());
        gdMsgHolidaySubModel.setDateEnd(now.getTime());

        gdMsgHolidaySubModel.setType(GdMsgHolidayModel.Type.DEFAULT);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        realmHelper.getRealm().close();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.gdmsg_new_holiday_fragment, container, false);

        final Calendar calendar = Calendar.getInstance();
        final DatePickerDialog datePickerDialog = DatePickerDialog.newInstance(this,
                calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        final TimePickerDialog timePickerDialog = TimePickerDialog.newInstance(this,
                calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true);

        tvStartDate = (TextView) view.findViewById(R.id.tvStartDate);
        tvFinishDate = (TextView) view.findViewById(R.id.tvFinishDate);
        tvStartTime = (TextView) view.findViewById(R.id.tvStartTime);
        tvFinishTime = (TextView) view.findViewById(R.id.tvFinishTime);

        EditText etComment = (EditText) view.findViewById(R.id.etComment);

        CheckBox cbVacation = (CheckBox) view.findViewById(R.id.cbVacation);

        SimpleDateFormat dateFormat = new SimpleDateFormat("d MMMM", Locale.getDefault());
        tvStartDate.setText(dateFormat.format(gdMsgHolidaySubModel.getDateBegin()));
        tvFinishDate.setText(dateFormat.format(gdMsgHolidaySubModel.getDateEnd()));

        tvStartDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                datePickerDialog.setYearRange(calendar.get(Calendar.YEAR), calendar.get(Calendar.YEAR) + 1);
                datePickerDialog.show(getActivity().getFragmentManager(), DATEPICKER_START_TAG);
            }
        });
        tvFinishDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                datePickerDialog.setYearRange(calendar.get(Calendar.YEAR), calendar.get(Calendar.YEAR) + 1);
                datePickerDialog.show(getActivity().getFragmentManager(), DATEPICKER_FINISH_TAG);
            }
        });

        tvStartTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                timePickerDialog.show(getActivity().getFragmentManager(), TIMEPICKER_START_TAG);
            }
        });
        tvFinishTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                timePickerDialog.show(getActivity().getFragmentManager(), TIMEPICKER_FINISH_TAG);
            }
        });

        etComment.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                gdMsgHoliday.setComment(s.toString());
            }
        });

        cbVacation.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked)
                    gdMsgHolidaySubModel.setType(GdMsgHolidayModel.Type.VACATION);
                else
                    gdMsgHolidaySubModel.setType(GdMsgHolidayModel.Type.DEFAULT);
            }
        });

        if (savedInstanceState != null) {
            DatePickerDialog dpd1 = (DatePickerDialog) getActivity().getFragmentManager().
                    findFragmentByTag(DATEPICKER_START_TAG);
            if (dpd1 != null) {
                dpd1.setOnDateSetListener(this);
            }
            DatePickerDialog dpd2 = (DatePickerDialog) getActivity().getFragmentManager().
                    findFragmentByTag(DATEPICKER_FINISH_TAG);
            if (dpd2 != null) {
                dpd2.setOnDateSetListener(this);
            }

            TimePickerDialog tpd1 = (TimePickerDialog) getActivity().getFragmentManager().
                    findFragmentByTag(TIMEPICKER_START_TAG);
            if (tpd1 != null) {
                tpd1.setOnTimeSetListener(this);
            }
            TimePickerDialog tpd2 = (TimePickerDialog) getActivity().getFragmentManager().
                    findFragmentByTag(TIMEPICKER_FINISH_TAG);
            if (tpd2 != null) {
                tpd2.setOnTimeSetListener(this);
            }
        }
        return view;
    }

    @Override
    public void onDateSet(DatePickerDialog datePickerDialog, int year, int month, int day) {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("d MMMM", Locale.getDefault());

        switch (datePickerDialog.getTag()) {
            case DATEPICKER_START_TAG:
                calendar.setTime(gdMsgHolidaySubModel.getDateBegin());
                calendar.set(year, month, day);
                gdMsgHolidaySubModel.getDateBegin().setTime(calendar.getTimeInMillis());

                tvStartDate.setText(dateFormat.format(gdMsgHolidaySubModel.getDateBegin()));
                break;
            case DATEPICKER_FINISH_TAG:
                calendar.setTime(gdMsgHolidaySubModel.getDateEnd());
                calendar.set(year, month, day);
                gdMsgHolidaySubModel.getDateEnd().setTime(calendar.getTimeInMillis());

                tvFinishDate.setText(dateFormat.format(gdMsgHolidaySubModel.getDateEnd()));
                break;
        }
    }

    @Override
    public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute) {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());

        switch ((String) view.getTag()) {
            case TIMEPICKER_START_TAG:
                calendar.setTime(gdMsgHolidaySubModel.getDateBegin());
                calendar.set(Calendar.HOUR, hourOfDay);
                calendar.set(Calendar.MINUTE, minute);
                gdMsgHolidaySubModel.getDateBegin().setTime(calendar.getTimeInMillis());

                tvStartTime.setText(dateFormat.format(gdMsgHolidaySubModel.getDateBegin()));
                break;
            case TIMEPICKER_FINISH_TAG:
                calendar.setTime(gdMsgHolidaySubModel.getDateEnd());
                calendar.set(Calendar.HOUR, hourOfDay);
                calendar.set(Calendar.MINUTE, minute);
                gdMsgHolidaySubModel.getDateEnd().setTime(calendar.getTimeInMillis());

                tvFinishTime.setText(dateFormat.format(gdMsgHolidaySubModel.getDateEnd()));
                break;
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_send:

                gdMsgHoliday.setUid(realmHelper.generateUID(GdMsgModel.class));
                gdMsgHoliday.setSender(GdMsgModel.Sender.CLIENT);
                gdMsgHoliday.setSubject(GdMsgModel.Subject.HOLIDAY);
                gdMsgHoliday.setRequestStatus(GdMsgModel.RequestStatus.UNKNOWN);
                gdMsgHoliday.setTimestamp(new Date());
                gdMsgHolidaySubModel.setUid(realmHelper.generateUID(GdMsgHolidayModel.class));
                gdMsgHoliday.setGdMsgHolidayModel(gdMsgHolidaySubModel);
                gdMsgHoliday.setGdMsgString(ExtractStringHelper.gdMsgToString(gdMsgHoliday));

                Intent intent = new Intent(getActivity(), SendMsgDataService.class);
                intent.setAction(SendMsgDataService.SEND_GD_MSG_ACTION);
                intent.putExtra(SendMsgDataService.EXTRA_KEY_GD_MSG, gdMsgHoliday);
                getActivity().startService(intent);

                getActivity().finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onResume() {
        super.onResume();
        Tracker tracker = ((App) getActivity().getApplication()).getTracker(App.TrackerName.APP_TRACKER);
        tracker.setScreenName(getClass().getSimpleName());
        tracker.send(new HitBuilders.AppViewBuilder().build());
    }
}
